//
//  Networking.swift
//  BodyBuilding
//
//  Created by franze on 2017/10/7.
//  Copyright © 2017年 franze. All rights reserved.
//

import UIKit
import AFNetworking

let BB_VIDEOURL         = "http://172.24.10.175/workout/Uploads/master/video/zjs/mvc1.mp4"
let BB_IMAGEURLPRE      = "http://172.24.10.175/workout/Uploads/"
let BB_REGISTER         = "http://172.24.10.175/workout/api.php/reg"
let BB_LOGIN            = "http://172.24.10.175/workout/api.php/login"
let BB_GETCLUBLIST      = "http://172.24.10.175/workout/api.php/lists/mod/club"
let BB_GETMASTERLIST    = "http://172.24.10.175/workout/api.php/lists/mod/master"
let BB_GETSHARINGLIST   = "http://172.24.10.175/workout/api.php/lists"
let BB_GETTRAININGLIST  = "http://172.24.10.175/workout/api.php/lists/mod/training"
let BB_POSTSHARING      = "http://172.24.10.175/workout/api.php/fcreate"
let BB_FOCUS_JOIN       = "http://172.24.10.175/workout/api.php/focus"
let BB_GETJOINEDCLUB    = "http://172.24.10.175/workout/api.php/get/mod/user"
let BB_LOGOUT           = "172.24.10.175/api.php/logout"
let BB_ISEXITS          = "http://172.24.10.175/workout/api.php/isExits/mod/fans"
let BB_DELETE           = "http://172.24.10.175/workout/api.php/delete/mod/fans"
let BB_CREAT            = "http://172.24.10.175/workout/api.php/create"
let BB_GETCLUBCOURSE    = "http://172.24.10.175/workout/api.php/get/map/Clubcourse"
let BB_COURSEDETAIL     = "http://172.24.10.175/workout/api.php/get/mod/train"

class Networking: NSObject {
    static var shared = Networking()
    private override init() {}
    private var sessionManager = AFHTTPSessionManager()
    private lazy var popup = Popup()
    
    func register(parameter:NSDictionary,block:@escaping ()->Void){
        sessionManager.post(BB_REGISTER, parameters: parameter, progress: nil, success: { (datatask, json) in
            let dict = json as! NSDictionary
            if let error = dict.value(forKey: "error"){
                self.popup.appear(title: error as! String, action: nil)
            }
            else{
                block()
            }
        }) { (dataTask, error) in
            self.popup.appear(title: "网络异常", action: nil)
        }
    }
    
    func login(parameter:NSDictionary,block:@escaping (Bool)->Void){
        sessionManager.post(BB_LOGIN, parameters: parameter, progress: nil, success: { (datatask, json) in
            let dict = json as! NSDictionary
            if let error = dict.value(forKey: "error"){
                self.popup.appear(title: error as! String, action: nil)
                block(false)
            }
            else{
                LoginModel.getUserInfo(dict: dict)
                block(true)
            }
        }) { (datatask, error) in
            self.popup.appear(title: "网络异常", action: nil)
            block(false)
        }
    }
    
    func getClubList(parameter:NSDictionary,block:@escaping (NSArray)->Void){
        sessionManager.post(BB_GETCLUBLIST, parameters: parameter, progress: nil, success: { (datatask, json) in
            let array = json as! NSArray
            block(array)
        }) { (datatask, error) in
            self.popup.appear(title: "网络异常", action: nil)
        }
    }
    
    func getMasterList(parameter:NSDictionary,block:@escaping (NSArray)->Void){
        sessionManager.post(BB_GETMASTERLIST, parameters: parameter, progress: nil, success: { (datatask, json) in
            let array = json as! NSArray
            block(array)
        }) { (datatask, error) in
            self.popup.appear(title: "网络异常", action: nil)
        }
    }
    
    func getSharingList(parameter:NSDictionary,block:@escaping (NSArray)->Void){
        sessionManager.post(BB_GETSHARINGLIST, parameters: parameter, progress: nil, success: { (datatask, json) in
            let array = json as! NSArray
            block(array)
        }) { (datatask, error) in
            self.popup.appear(title: "网络异常", action: nil)
        }
    }
    
    func getTrainingList(parameter:NSDictionary,block:@escaping (NSArray)->Void){
        sessionManager.post(BB_GETTRAININGLIST, parameters: parameter, progress: nil, success: { (datatask, json) in
            let array = json as! NSArray
            block(array)
        }) { (datatask, error) in
            self.popup.appear(title: "网络异常", action: nil)
        }
    }
    
    func postSharing(parameter:NSDictionary,image:UIImage,block:@escaping ()->Void){
        sessionManager.post(BB_POSTSHARING, parameters: parameter, constructingBodyWith: { (fromData) in
            if let data = UIImageJPEGRepresentation(image, 0.1){
                fromData.appendPart(withFileData: data, name: "thumb0", fileName: "image.jpeg", mimeType: "image/jpeg")
            }else{
                let data = UIImageJPEGRepresentation(UIImage(named:"placeholder")!,0.1)
                fromData.appendPart(withFileData: data!, name: "thumb0", fileName: "image.jpeg", mimeType: "image/jpeg")
            }

        }, progress: nil, success: { (task, json) in
            block()
        }) { (task, error) in
            block()
        }
    }
    
    func focus_Join(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: BB_FOCUS_JOIN, parameter: parameter, block: nil)
        block()
    }
    
    func getJoinedClub(parameter:NSDictionary,block:@escaping (NSDictionary)->Void){
        sessionManager.post(BB_GETJOINEDCLUB, parameters: parameter, progress: nil, success: { (datatask, json) in
            let dict = json as! NSDictionary
            block(dict)
        }) { (datatask, error) in
            self.popup.appear(title: "网络异常", action: nil)
        }
    }
    
    func logout(block:@escaping ()->Void){
        post(urlStr: BB_LOGOUT, parameter: ["SessionID":LoginModel.sessionID], block: nil)
        block()
    }
    
    func isExits(parameter:NSDictionary,block:@escaping (Bool)->Void){
        post(urlStr: BB_ISEXITS, parameter: parameter) { (json) in
            if let dict = json as? NSDictionary{
                DispatchQueue.main.async {
                    self.popup.appear(title: dict.value(forKey: "error") as! String, action: nil)
                }
            }else{
                let str = json as! String
                if str == "0"{
                    block(true)
                }else{
                    block(false)
                }
            }
        }
    }
    
    func delete(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: BB_DELETE, parameter: parameter, block: nil)
        block()
    }
    
    func creat(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: BB_CREAT, parameter: parameter, block: nil)
        block()
    }
    
    func fetchImage(block:@escaping (NSArray)->Void){
        sessionManager.post("http://172.24.10.175/workout/api.php/lists/mod/itempos/SessionID/2ul9sj8vlfofj122e1s98048k2/related/1/posid/1", parameters: nil, progress: nil, success: { (datatask, json) in
            block(json as! NSArray)
        }, failure: nil)
    }
    
    func getCourse(parameter:NSDictionary,block:@escaping (NSDictionary)->Void){
        sessionManager.post(BB_GETCLUBCOURSE, parameters: parameter, progress: nil, success: { (datatask, json) in
            block(json as! NSDictionary)
        }, failure: nil)
    }
    
    func getCourseDetail(parameter:NSDictionary,block:@escaping (NSDictionary)->Void){
        sessionManager.post(BB_COURSEDETAIL, parameters: parameter, progress: nil, success: { (datatask, json) in
            block(json as! NSDictionary)
        }, failure: nil)
    }
    
    private func post(urlStr:String,parameter:NSDictionary,block:((_ data:Any?)->Void)?){
        let paraArray = NSMutableArray()
        for (key,value) in parameter{
            let str = "\(key)=\(value)"
            paraArray.add(str)
        }
        let body = paraArray.componentsJoined(by: "&")
        var request = URLRequest(url: URL(string: urlStr)!)
        request.httpMethod = "post"
        request.httpBody = body.data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if data != nil{
                if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers){
                    block!(json)
                }
                else{
                    if let str = String(data: data!, encoding: String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)))){
                        print(str)
                        block?(str)
                    }else if let str = String(data: data!, encoding: .utf8){
                        print(str)
                        block?(str)
                    }
                }
            }else{
                print("返回为空")
                print(error.debugDescription)
            }
        }
        task.resume()
    }

}
